let WebSocket = require('ws')
let redis = require('redis')
const WebSocketServer = WebSocket.Server;

let client = redis.createClient()

let wss = new WebSocketServer({ port: 3000 })
// 原生的WebSocket两个常用的方法
let clientArr = []
wss.on('connection', function (ws) {
  clientArr.push(ws)
  client.lrange('barrages', 0, -1, function (err, applist) {
    applist = applist.map(item => JSON.parse(item))
    ws.send(JSON.stringify({
      type: 'init',
      data: applist
    }))
  })
  ws.on('message', function (data) { // 监听客户端发来的数据
    client.rpush('barrages', data, redis.print) // 把数据放到redis里去
    clientArr.forEach((w) => {
      w.send(JSON.stringify({ type: 'add', data: JSON.parse(data) }))
    })
  })
  ws.on('close', function () {
    clientArr = clientArr.filter(client => client !== ws)
  })
})